<script lang="ts" setup>
import userHeader from '../userHeader.vue'
import flowPath from '../flowPath.vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import uploadFile from '@/components/uploadFile.vue'
import utilsService from '@/api/utilsService'
import userService from '@/api/userService'
import { useRouter } from 'vue-router'

const router = useRouter()

const formLabelAlign: { [key: string]: any } = reactive({
  userId: '',
  verificationName: '',
  verificationId: '',
  verificationIDCaedFront: new Blob(),
  verificationIDCardBack: new Blob(),
  verificationIDCardHolding: new Blob(),
  way: '个人认证'
})

const srcObj: { [key: string]: any } = reactive({
  verificationIDCaedFront: '',
  verificationIDCardBack: '',
  verificationIDCardHolding: ''
})

const getVerificationIDCaedFront = (file: Blob) => {
  const formData = new FormData()
  formData.append('file', file)
  formData.append('fileType', '1')
  formData.append('userId', localStorage.getItem('userId') as string)
  utilsService.uploadFile(formData).then((res) => {
    if (res.status === 200) {
      showImage(file, 'verificationIDCaedFront')
      formLabelAlign.verificationIDCaedFront = file
    }
  })
}
const getVerificationIDCardBack = (file: Blob) => {
  const formData = new FormData()
  formData.append('file', file)
  formData.append('fileType', '1')
  formData.append('userId', localStorage.getItem('userId') as string)
  utilsService.uploadFile(formData).then((res) => {
    if (res.status === 200) {
      showImage(file, 'verificationIDCardBack')
      formLabelAlign.verificationIDCardBack = file
    }
  })
}
const getVerificationIDCardHolding = (file: Blob) => {
  const formData = new FormData()
  formData.append('file', file)
  formData.append('fileType', '1')
  formData.append('userId', localStorage.getItem('userId') as string)
  utilsService.uploadFile(formData).then((res) => {
    if (res.status === 200) {
      showImage(file, 'verificationIDCardHolding')
      formLabelAlign.verificationIDCardHolding = file
    }
  })
}

const checkUserId = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入身份证号！'))
  } else {
    if (
      !/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/.test(value)
    ) {
      callback(new Error('身份证格式错误'))
    } else {
      callback()
    }
  }
}
const showImage = (file: Blob, imgHander: string) => {
  let render = new FileReader()
  render.readAsDataURL(file)
  render.onload = function (e) {

    srcObj[imgHander] = this.result
  }
}
const clearImg = (imgHander: string) => {
  formLabelAlign[imgHander] = new Blob()
  srcObj[imgHander] = ''
}
const checkVerificationIDCaedFront = (rule: any, value: Blob, callback: any) => {
  if (!value.size) {
    callback(new Error('请选择身份证图片！'))
  } else {
    callback()
  }
}

const ruleFormRef = ref<FormInstance>()

const rules = reactive<FormRules>({
  way: [{ required: true, message: '认证方式必选', trigger: 'blur' }],
  verificationName: [
    {
      required: true,
      message: '姓名不能为空',
      trigger: 'blur'
    }
  ],
  userId: [
    {
      required: true,
      validator: checkUserId,
      trigger: 'change'
    }
  ],
  verificationIDCaedFront: [
    {
      required: true,
      validator: checkVerificationIDCaedFront,
      trigger: 'change'
    }
  ],
  verificationIDCardBack: [
    {
      required: true,
      validator: checkVerificationIDCaedFront,
      trigger: 'change'
    }
  ],
  verificationIDCardHolding: [
    {
      required: true,
      validator: checkVerificationIDCaedFront,
      trigger: 'change'
    }
  ],
  verificationId: [
    {
      required: true,
      message: 'Please pick a time',
      trigger: 'change'
    }
  ]
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      userService
        .userAuthentication({
          userId: localStorage.getItem('userId'),
          verificationName: formLabelAlign.verificationName,
          verificationId: formLabelAlign.userId
        })
        .then((res) => {
          if (res.data.code) {
            ElMessage.error(res.data.msg)
          } else {
            ElMessage.success('提交成功')
          }
        })
    }
  })
}

const isAuth = sessionStorage.getItem('AUTHEN') as string
const goSetting = () => {
  router.push({ name: 'BasicInformation' })
}

watch(
  () => formLabelAlign.way,
  (n) => {
  }
)
</script>
<template>
  <div class="auth">
    <div v-if="isAuth === '0'">
      <el-row>
        <el-col :span="24">
          <user-header></user-header>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="18">
          <div class="content-box">
            <div class="verification-title"><span>填写认证资料</span></div>
            <div class="verification-box">
              <el-form ref="ruleFormRef" :model="formLabelAlign" :rules="rules" label-width="120px" class="attestation"
                status-icon>
                <el-form-item label="认证类型" prop="way">
                  <el-radio-group v-model="formLabelAlign.way" plain>
                    <el-radio-button label="个人认证" value="0" />
                    <el-radio-button label="企业认证" value="1" />
                  </el-radio-group>
                </el-form-item>
                <template v-if="formLabelAlign.way === '个人认证'">
                  <el-form-item label="个人姓名" prop="verificationName">
                    <el-input v-model="formLabelAlign.verificationName" style="width: 360px" placeholder="请输入姓名" />
                    <span style="color: #9198a4; margin-left: 20px">姓名、银行卡/支付宝户名、证件对应个人姓名必须一致</span>
                  </el-form-item>
                  <el-form-item label="身份证号码" prop="userId">
                    <el-input v-model="formLabelAlign.userId" style="width: 360px" placeholder="请输入身份证号码" />
                    <span style="color: #9198a4; margin-left: 20px">认证后无法修改，请认真填写</span>
                  </el-form-item>
                  <el-form-item label="身份证正面" prop="verificationIDCaedFront">
                    <upload-file @get-fils="getVerificationIDCaedFront" :max-size="2">
                      <template v-slot:btn v-if="formLabelAlign.verificationIDCaedFront.size">
                        <div style="position: relative">
                          <el-icon class="close" @click="clearImg('verificationIDCaedFront')">
                            <Close />
                          </el-icon>
                          <el-image id="verificationIDCaedFront" style="width: 76px; height: 76px; cursor: zoom-in"
                            :src="srcObj.verificationIDCaedFront" :zoom-rate="1.2"
                            :preview-src-list="[srcObj.verificationIDCaedFront]" :initial-index="4" fit="cover" />
                        </div>
                      </template>
                      <template v-slot:right>
                        <div class="file-type">支持JEPG格式，文件大小不超过2MB。请上传身份证正面</div>
                        <span class="text-info">示例：身份证正面</span>
                      </template>
                    </upload-file>
                  </el-form-item>
                  <el-form-item label="身份证反面" prop="verificationIDCardBack">
                    <upload-file @get-fils="getVerificationIDCardBack" :max-size="2">
                      <template v-slot:btn v-if="formLabelAlign.verificationIDCardBack.size">
                        <div style="position: relative">
                          <el-icon class="close" @click="clearImg('verificationIDCardBack')">
                            <Close />
                          </el-icon>
                          <el-image id="verificationIDCardBack" style="width: 76px; height: 76px; cursor: zoom-in"
                            :src="srcObj.verificationIDCardBack" :zoom-rate="1.2"
                            :preview-src-list="[srcObj.verificationIDCardBack]" :initial-index="4" fit="cover" />
                        </div>
                      </template>
                      <template v-slot:right>
                        <div class="file-type">支持JEPG格式，文件大小不超过2MB。请上传身份证反面</div>
                        <span class="text-info">示例：身份证反面</span>
                      </template>
                    </upload-file>
                  </el-form-item>
                  <el-form-item label="手持身份证" prop="verificationIDCardHolding">
                    <upload-file @get-fils="getVerificationIDCardHolding" :max-size="2">
                      <template v-slot:btn v-if="formLabelAlign.verificationIDCardHolding.size">
                        <div style="position: relative">
                          <el-icon class="close" @click="clearImg('verificationIDCardHolding')">
                            <Close />
                          </el-icon>
                          <el-image id="verificationIDCardHolding" style="width: 76px; height: 76px; cursor: zoom-in"
                            :src="srcObj.verificationIDCardHolding" :zoom-rate="1.2"
                            :preview-src-list="[srcObj.verificationIDCardHolding]" :initial-index="4" fit="cover" />
                        </div>
                      </template>
                      <template v-slot:right>
                        <div class="file-type">支持JEPG格式，文件大小不超过2MB。请上传身份证反面</div>
                        <span class="text-info">示例：手持身份证</span>
                      </template>
                    </upload-file>
                  </el-form-item>
                </template>
                <template v-else> 企业认证 </template>
                <el-form-item>
                  <el-button type="primary" @click="submitForm(ruleFormRef)"> 提交审核 </el-button>
                </el-form-item>
              </el-form>
            </div>

            <div class="warnings">
              <div class="left">!</div>
              <div class="right">
                <div style="color: #ff7500; font-size: 14px; margin-left: 20px">提交虚假认证材料，面临账户冻结风险</div>
                <span>1. PRIM转售综合管理平台将对您的资料进行严格保密</span>
                <span>2. 认证材料一经通过审核后无法修改，可以转换认证类型</span>
                <span>3. 请上传清晰度较高的图片，模糊不清的图片将导致审核不通过</span>
                <span>4. 客服人员将在收到人则会那个材料之后的1-24小时内审核，周末及法定假日顺延</span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6"> <flow-path></flow-path> </el-col>
      </el-row>
    </div>
    <el-row style="padding-top: 15%;" v-else>
      <el-col>
        <el-result icon="success" title="认证成功" sub-title="您已完成认证">
          <template #extra>
            <el-button type="primary" @click="goSetting">去查看认证信息</el-button>
          </template>
        </el-result>
      </el-col>
    </el-row>
  </div>
</template>

<style lang="scss" scoped>
.auth {
  height: 79vh;
  background-color: #fff;
}

.close {
  position: absolute;
  top: 1px;
  right: 1px;
  z-index: 10;
  cursor: pointer;
}

.upload {
  .right {
    div {
      color: var(--el-text-color-primary);
    }

    span {
      color: var(--el-color-primary);
    }
  }
}

.attestation {
  margin-top: 40px;
  margin-left: 130px;
}

.el-row {
  margin-bottom: 20px;
}

.warnings {
  height: 160px;
  display: flex;
  align-items: center;
  margin: 0 30px;
  background: rgba(255, 117, 0, 0.1);
  border-left: 4px solid #ff7500;

  .left {
    width: 44px;
    height: 44px;
    border: 3px solid #ff7500;
    color: #ff7500;
    font-size: 36px;
    text-align: center;
    line-height: 44px;
    border-radius: 50%;
    margin-left: 24px;
  }

  .right {
    div {
      margin-bottom: 10px;
    }

    span {
      display: block;
      font-size: 14px;
      color: #556279;
      margin-left: 20px;
    }
  }
}

.content-box {
  background: $blank-color;
  height: 830px;

  .upload-demo {
    height: 116px !important;
    width: 116px !important;
  }

  .verification-title {
    height: 69px;
    display: flex;
    padding: 0 30px;
    align-items: center;
    font-size: 18px;
    font-weight: 700;
    color: $text-color;
    border-bottom: 1px solid $border-color;
    justify-content: space-between;

    .verification-box {
      margin: 0 auto;
      width: 480px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: space-between;
    }

    .el-alert:first-child {
      margin: 0;
    }
  }
}
</style>
